package com.yunquan.ohana.ui.calendar.task

import android.os.Bundle
import androidx.core.graphics.toColorInt
import androidx.databinding.ObservableField
import com.google.gson.Gson
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.ui.ItemViewModel
import com.yunquan.ohana.entity.TaskEntity
import com.yunquan.ohana.entity.UserManager
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.ui.calendar.task.add.TaskAddActivity
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import okhttp3.RequestBody.Companion.toRequestBody
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter

class TaskItemViewModel(viewModel: TaskViewModel) : ItemViewModel<TaskViewModel>(viewModel) {

    var data: TaskEntity? = null

    val title = ObservableField<String>()
    val emoji = ObservableField<String>()
    val dateTime = ObservableField<String>()
    val rolePrefix = ObservableField<String>()
    val inner = ObservableField<Int>()
    val outer = ObservableField<Int>()
    val status = ObservableField<Boolean>(false)
    val isChecked = ObservableField(false)
    val checked = ObservableField(false)
    val checkedIcon = ObservableField<Int>()

    constructor(viewModel: TaskViewModel, data: TaskEntity, isCheck: Boolean = false) : this(viewModel) {
        this.data = data
        this.title.set(data.title)
        this.emoji.set(data.emoji)
        this.isChecked.set(isCheck)
        this.checked.set(data.status == 1.0)
        this.status.set(data.status == 1.0)
        val startDateTime = LocalDateTime.ofInstant(
            Instant.ofEpochSecond(data.reminderTime?.toLong() ?: data.startDate?.toLong() ?: 0),
            ZoneId.systemDefault(),
        )
        this.dateTime.set(startDateTime.format(DateTimeFormatter.ofPattern("HH:mm")))
        if (data.tasksToRoleVos?.isNotEmpty() == true) {
            val role = data.tasksToRoleVos!!.first()
            role.roleId == UserManager.instance.getUser()?.id
            this.rolePrefix.set(role.roleName?.first()?.toString())
            this.inner.set(role.getColorData().inner.toColorInt())
            this.outer.set(role.getColorData().outer.toColorInt())
            if (role.status == 1) {
                this.checkedIcon.set(R.mipmap.ic_lists_list_check)
            } else {
                this.checkedIcon.set(R.mipmap.ic_lists_list_normal)
            }
        } else {
            this.checkedIcon.set(R.mipmap.ic_lists_list_normal)
            this.inner.set(Utils.instance.context.getColor(R.color.c_FF9932))
            this.outer.set(Utils.instance.context.getColor(R.color.c_FFF6ED))
        }
    }

    val onCheckChange = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            updateStatus()
        }
    })

    val onDeleteClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            viewModel.onDeleteTask(data!!)
        }
    })

    val onItemClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("deviceId", viewModel.mDeviceId)
            bundle.putString("roleId", viewModel.mRoleId)
            bundle.putBoolean("userType", viewModel.mUserType)
            bundle.putString("data", Gson().toJson(data))
            viewModel.startActivityResult(TaskAddActivity::class.java, bundle)
        }
    })

    private fun updateStatus() {
        val now = LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0))
        val map = mutableMapOf<String, Any?>()
        map["tasksId"] = data?.id
        map["deviceId"] = viewModel.mDeviceId
        map["status"] = if (checked.get() == false) 1 else 0
        map["roleIds"] = listOf(viewModel.mCurrentRole?.id)
        map["instanceDate"] = now.atZone(ZoneId.systemDefault()).toEpochSecond()
        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.updateTasksToStautsByDeviceId(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    viewModel.showLoading()
                }

                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        viewModel.getTaskList()

                        val b = checked.get() ?: false
                        checked.set(!b)
                        if (checked.get() == true) {
                            checkedIcon.set(R.mipmap.ic_lists_list_check)
                        } else {
                            checkedIcon.set(R.mipmap.ic_lists_list_normal)
                        }
                    } else {
                        viewModel.hideLoading()
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    viewModel.hideLoading()
                }
            })
    }
}